<?php
class ControlStock
{
	public function isHaveStock($userid, $stockid)
	{
		include $_SERVER['DOCUMENT_ROOT'].'scue'.'/configuration.php';
		$sql = "SELECT * FROM userstock WHERE (stockid ='$stockid') AND (userid = '$userid')";
		if(!($result = mysql_query($sql))) die(mysql_error());
		$row = mysql_fetch_array($result);
		return intval($row['Amount']);
	}

	public function changeUserStock($userid, $stockid, $amount)
	{
		if ($amount < 1)
		{
			$sql = "DELETE FROM userstock WHERE (stockid ='$stockid') AND (userid = '$userid')";
			mysql_query($sql);
		}
		else
		{
			$sql = "UPDATE userstock SET Amount='$amount' WHERE (stockid ='$stockid') AND (userid = '$userid')";
			mysql_query($sql);
		}
	}

	public function insertUserSotck($userid, $stockid, $amount)
	{
		$sql = "INSERT INTO userstock (UserID, StockID, Amount) VALUES ('$userid','$stockid','$amount')";
		mysql_query($sql);
	}

	public function addUserStock($userid, $stockid, $amount)
	{
		$temp = $this->isHaveStock($userid, $stockid);
		if ($temp > 0)
		$this->changeUserStock($userid, $stockid, $amount + $temp);
		else
		$this->insertUserSotck($userid, $stockid, $amount);
	}

	public function subUserStock($userid, $stockid, $amount)
	{
		$temp = $this->isHaveStock($userid, $stockid);
		if ($temp > 0)
		$this->changeUserStock($userid, $stockid, $temp - $amount);
	}
}
?>
